﻿using System;
using System.Web;
using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;

namespace DemoSite.api
{
    /// <summary>
    /// upload 的摘要说明
    /// </summary>
    public class upload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;

            int c = request.Files.Count;


            //接收上传的数据并保存到服务器
            for (int i = 0; i < c; i++)
            {
                HttpPostedFile file = request.Files[i];

                string fileName = request["fileName"];
                if (string.IsNullOrEmpty(fileName)) fileName = System.IO.Path.GetFileName(file.FileName);


                string path = context.Server.MapPath("~/upload/" + fileName);

                file.SaveAs(path);

            
            }


            string type = request["type"];
            string user = request["user"];
            string uid = request["uid"];
            string filepath = "~/upload/" + request["fileName"];

            string sqlconnstr = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
            MySqlConnection sqlconn = new MySqlConnection(sqlconnstr);
            sqlconn.Open();
            string userid = "80";
            string sqlstr = "update user set userlogo='" + filepath + "' where id=" + userid; ;
            MySqlCommand sqlcom = new MySqlCommand();
            sqlcom.Connection = sqlconn;
            sqlcom.CommandText = sqlstr;
            sqlcom.ExecuteNonQuery();
            sqlconn.Close();
            //sqlconn = null;

            //此处返回的JSON字符串为手动拼接,未处理字符串转义等特殊情况,仅作演示
            string json = "\"time\":\"" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\"";
            if (type != null) json += ",\"type\":\"" + type + "\"";
            if (user != null) json += ",\"user\":\"" + user + "\"";
            if (uid != null) json += ",\"uid\":\"" + uid + "\"";

            Finish("{" + json + "}");



        }

        /// <summary>
        /// 完成上传
        /// </summary>
        /// <param name="json">回调函数参数</param>
        private void Finish(string json)
        {
            HttpResponse Response = HttpContext.Current.Response;

            Response.Write(json);
            Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}





